package co.yixiang.yshop.module.store.service.webprint;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import co.yixiang.yshop.framework.common.exception.ErrorCode;
import co.yixiang.yshop.framework.common.pojo.PageResult;
import co.yixiang.yshop.framework.redis.util.redis.RedisUtil;
import co.yixiang.yshop.module.store.controller.admin.webprint.vo.WebPrintCreateReqVO;
import co.yixiang.yshop.module.store.controller.admin.webprint.vo.WebPrintExportReqVO;
import co.yixiang.yshop.module.store.controller.admin.webprint.vo.WebPrintPageReqVO;
import co.yixiang.yshop.module.store.controller.admin.webprint.vo.WebPrintUpdateReqVO;
import co.yixiang.yshop.module.store.convert.webprint.WebPrintConvert;
import co.yixiang.yshop.module.store.dal.dataobject.webprint.WebPrintDO;
import co.yixiang.yshop.module.store.dal.mysql.webprint.WebPrintMapper;
import co.yixiang.yshop.module.store.dal.redis.PrintTokenRedisDAO;
import co.yixiang.yshop.module.store.service.webprint.dto.ResponseData;
import co.yixiang.yshop.module.store.service.webprint.dto.TokeData;
import com.yly.java.yly_sdk.RequestMethod;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

import static co.yixiang.yshop.framework.common.exception.util.ServiceExceptionUtil.exception;
import static co.yixiang.yshop.module.store.enums.ErrorCodeConstants.WEB_PRINT_NOT_EXISTS;

/**
 * 易联云打印机 Service 实现类
 *
 * @author yshop
 */
@Service
@Validated
public class WebPrintServiceImpl implements WebPrintService {

    @Resource
    private WebPrintMapper webPrintMapper;
    @Resource
    private PrintTokenRedisDAO printTokenRedisDAO;


    //private static String clientId = RedisUtil.get("printClientId");

   // private static String clientSecret = RedisUtil.get("printClientSecret");



    @PostConstruct
    public static void initYlyMethod() {
        String clientId = RedisUtil.get("printClientId");
        String clientSecret = RedisUtil.get("printClientSecret");
        RequestMethod.init(clientId,clientSecret);
    }

    @Override
    public Long createWebPrint(WebPrintCreateReqVO createReqVO) {
        // 插入
        WebPrintDO webPrint = WebPrintConvert.INSTANCE.convert(createReqVO);

        //添加打印机
        String token = this.getToken();
        try {
            String res = RequestMethod.getInstance()
                    .addPrinter(createReqVO.getMechineCode(),createReqVO.getMsign(),token);

            ResponseData responseData = JSONUtil.toBean(res,ResponseData.class);
            if(responseData.getError() != 0) {
                throw exception(new ErrorCode(999992,responseData.getErrorDescription()));
            }
        } catch (Exception e) {
            throw exception(new ErrorCode(999991,e.getMessage()));
        }

        webPrintMapper.insert(webPrint);
        // 返回
        return webPrint.getId();
    }

    @Override
    public void updateWebPrint(WebPrintUpdateReqVO updateReqVO) {
        // 校验存在
        WebPrintDO webPrintDO = validateWebPrintExists(updateReqVO.getId());
        //先删除
        //if(!webPrintDO.getMechineCode().equals(updateReqVO.getMechineCode())){
            String token = this.getToken();
            try {
                String res1 =RequestMethod.getInstance().printerDeletePrinter(token,webPrintDO.getMechineCode());
                ResponseData responseData1 = JSONUtil.toBean(res1,ResponseData.class);
                if(responseData1.getError() != 0) {
                    throw exception(new ErrorCode(999992,responseData1.getErrorDescription()));
                }
                String res = RequestMethod.getInstance()
                        .addPrinter(updateReqVO.getMechineCode(),updateReqVO.getMsign(),token);

                ResponseData responseData = JSONUtil.toBean(res,ResponseData.class);
                if(responseData.getError() != 0) {
                    throw exception(new ErrorCode(999992,responseData.getErrorDescription()));
                }
            } catch (Exception e) {
                throw exception(new ErrorCode(999991,e.getMessage()));
            }
      //  }
        // 更新
        WebPrintDO updateObj = WebPrintConvert.INSTANCE.convert(updateReqVO);
        webPrintMapper.updateById(updateObj);
    }

    @Override
    public void deleteWebPrint(Long id) {
        // 校验存在
        WebPrintDO webPrintDO = validateWebPrintExists(id);
        //解绑打印机
        String token = this.getToken();
        try {
            String res =RequestMethod.getInstance().printerDeletePrinter(token,webPrintDO.getMechineCode());
            ResponseData responseData = JSONUtil.toBean(res,ResponseData.class);
            if(responseData.getError() != 0) {
                throw exception(new ErrorCode(999992,responseData.getErrorDescription()));
            }
        } catch (Exception e) {
            throw exception(new ErrorCode(999996,e.getMessage()));
        }

        // 删除
        webPrintMapper.deleteById(id);
    }

    private WebPrintDO validateWebPrintExists(Long id) {
        WebPrintDO webPrintDO = webPrintMapper.selectById(id);
        if (webPrintMapper.selectById(id) == null) {
            throw exception(WEB_PRINT_NOT_EXISTS);
        }
        return webPrintDO;
    }

    @Override
    public WebPrintDO getWebPrint(Long id) {
        return webPrintMapper.selectById(id);
    }

    @Override
    public List<WebPrintDO> getWebPrintList() {
        return webPrintMapper.selectList();
    }

    @Override
    public PageResult<WebPrintDO> getWebPrintPage(WebPrintPageReqVO pageReqVO) {
        return webPrintMapper.selectPage(pageReqVO);
    }

    @Override
    public List<WebPrintDO> getWebPrintList(WebPrintExportReqVO exportReqVO) {
        return webPrintMapper.selectList(exportReqVO);
    }

    /**
     * 小票打印
     * @param mechineCode 设备号
     * @param content 打印内容
     * @param originId  订单号
     * @return
     */
    @Override
    public String printOrder(String mechineCode, String content, String originId) {
        String token = this.getToken();
        try {
            String json = RequestMethod.getInstance().printIndex(token,mechineCode,content,originId);
            ResponseData responseData = JSONUtil.toBean(json,ResponseData.class);
            if(responseData.getError() != 0) {
                throw exception(new ErrorCode(999992,responseData.getErrorDescription()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw exception(new ErrorCode(9999923,e.getMessage()));
        }
        return null;
    }

    /**
     * 获取打印机token
     * @return
     */
    private String getToken(){
        String token = printTokenRedisDAO.get();
        if(StrUtil.isEmpty(token)) {
            try {
                String jsonStr = RequestMethod.getAccessToken();
                JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
                TokeData tokeData = jsonObject.get("body", TokeData.class);
                token = tokeData.getAccessToken();
                printTokenRedisDAO.set(token);
            } catch (Exception e) {
                throw exception(new ErrorCode(99999,e.getMessage()));
            }
        }

        return token;
    }





}
